<template>
  <el-card class="test-questions">
    <div class="header">
      <div v-if="add">试题录入</div>
      <div v-else-if="edit">试题修改</div>
      <hr class="hr-line" />
    </div>

    <el-form
      :model="questionForm"
      label-width="120px"
      ref="formRef"
      :rules="rules"

    >
      <el-form-item label="学科：" prop="subjectID" style="width:50%">
        <el-select v-model="questionForm.subjectID" placeholder="请选择">
          <el-option
            v-for="item in subjectOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录：" prop="catalogID" style="width:50%">
        <el-select
          v-model="questionForm.catalogID"
          placeholder="请选择"
          @focus="focusSubject"
        >
          <el-option
            v-for="item in catalogOption"
            :key="item.id"
            :label="item.directoryName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="企业：" prop="enterpriseID" style="width:50%">
        <el-select v-model="questionForm.enterpriseID" placeholder="请选择">
          <el-option
            v-for="item in companyOption"
            :key="item.id"
            :label="item.company"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="城市：" prop="province" style="width:50%">
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-select
              v-model="questionForm.province"
              placeholder="请选择"
              @change="changeCity"
            >
              <el-option
                v-for="item in provincesOption"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-select v-model="questionForm.city" placeholder="请选择">
              <el-option
                v-for="item in areaOption"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="方向：" prop="direction" style="width:50%">
        <el-select v-model="questionForm.direction" placeholder="请选择">
          <el-option
            v-for="item in directionOption"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="题型：" prop="questionType" style="width:50%">
        <el-radio
          v-model="questionForm.questionType"
          v-for="item in questionTypeOption"
          :key="item.value"
          :label="item.value"
          >{{ item.label }}</el-radio
        >
      </el-form-item>
      <el-form-item label="难度：" prop="difficulty" style="width:50%">
        <el-radio
          v-model="questionForm.difficulty"
          v-for="item in difficultyOption"
          :key="item.value"
          :label="item.value"
          >{{ item.label }}</el-radio
        >
      </el-form-item>
       <el-form-item label="题干：" prop="question" >
          <quillEditor
          style="height:180px;margin-bottom: 50px;"
            v-model="questionForm.question"
             :options="editorOption"
            @blur="$refs.formRef.validateField('question')"
          ></quillEditor>
        </el-form-item>
 <!-- 单选 -->
        <template v-if="questionForm.questionType === '1'" >
          <div v-for="(item, index) in arr" :key="index">
            <el-row v-if="index < 4">
              <el-col>
                <el-form-item label-width="120px" label="选项：">
                  <el-row>
                    <el-col :span="1">
                      <el-radio :label="index" v-model="radio">{{ item.code }}：</el-radio>
                    </el-col>
                    <el-col :span="5"> <el-input v-model="item.title"></el-input> </el-col>
                    <el-col :span="10">
                      <el-upload class="upload-demo" action="#" multiple :limit="3">
                        <el-button class="upload_btn">点击上传</el-button>
                      </el-upload>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-row>
            <el-col>
              <el-button class="add_btn" type="danger" size="small" @click="addItem" disabled>+增加选项与答案</el-button>
            </el-col>
          </el-row>
        </template>

        <!-- 多选 -->
        <template v-if="questionForm.questionType === '2'">
          <div v-for="(item, index) in arr" :key="index">
            <el-checkbox-group v-model="checkList">
              <el-row v-if="index < questionIndex">
                <el-col>
                  <el-form-item label-width="120px" label="选项：">
                    <el-row>
                      <el-col :span="1">
                        <el-checkbox :label="index">{{ item.code }}</el-checkbox>
                      </el-col>
                      <el-col :span="5"> <el-input v-model="item.title"></el-input> </el-col>
                      <el-col :span="10">
                        <el-upload class="upload-demo" action="#" multiple :limit="3">
                          <el-button class="upload_btn">点击上传</el-button>
                        </el-upload>
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-checkbox-group>
          </div>
          <el-row>
            <el-col>
              <el-button class="add_btn" type="danger" size="small" @click="addItem">+增加选项与答案</el-button>
            </el-col>
          </el-row>
        </template>
          <el-form-item  label="解析视频：" style="width:50%">
              <el-input v-model="questionForm.videoURL"></el-input>
            </el-form-item>
             <el-form-item label="答案解析：" prop="question" >
          <quillEditor
          style="height:180px;margin-bottom: 50px;"
            v-model="questionForm.answer"
             :options="editorOption"
            @blur="$refs.formRef.validateField('question')"
          ></quillEditor>
        </el-form-item>
         <el-form-item label="题目备注：" prop="remarks" style="width:50%">
        <el-input
          v-model="questionForm.remarks"
          type="textarea"
          :rows="4"
          ></el-input
        >
      </el-form-item>
       <el-form-item label="试题标签：" prop="tags" style="width:50%">
        <el-select v-model="questionForm.tags" multiple  placeholder="请选择">
          <el-option
            v-for="item in tagsOption"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item >
        <el-button :type="$route.query.id ? 'success ' : 'primary'" @click="save($event)">{{ $route.query.id ? '确认修改' : '确认提交' }}</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { simpleSubject } from '@/api/hmmm/subjects'
import { list } from '@/api/hmmm/directorys'
import { companyList } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction, questionType, difficulty, array } from '@/api/hmmm/constants'
import { simpleTag } from '@/api/hmmm/tags'
import { add, detail, update } from '@/api/hmmm/questions'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
export default {
  components: {
    quillEditor
  },
  async created () {
    this.simpleSubject()
    this.companyList()
    this.provinces()
    this.simpleTag()

    if (this.$route.query.id) {
      this.add = false
      this.edit = true
      const { data } = await detail(this.$route.query.id)

      this.questionForm = data
      this.questionForm.tags = data.tags.split(',')
      this.questionIndex = this.questionForm.options.length
      // 重新加载添加按钮所需的容器
      const array1 = array
      // 对添加按钮的数据进行处理
      const newArr = array1.splice(+this.questionForm.options.length)
      this.arr = this.questionForm.options.concat(newArr)

      switch (this.questionForm.questionType) {
        // 单选
        case '1':

          this.questionForm.options.forEach((item, index) => {
            if (item.isRight === 1) {
              this.radio = index
            }
          })
          break
          // 多选
        case '2':
          this.questionForm.options.forEach((item, index) => {
            if (item.isRight === 1) {
              this.checkList.push(index)
            }
          })
          break
      }

      // // 返回顶部
      // this.backTop()
    } else {
      this.add = true
      this.edit = false
    }
  },
  watch: {
    '$route.query.id' () {
      ++this.key
      this.$router.go(0)
      this.getQuestionsInfo()
    }
  },
  data () {
    return {
      key: 1,
      // 复选框列表
      checkList: [],
      // 单选
      radio: '',
      // 选项存储的index
      questionIndex: 4,
      // 存储选项的数组
      arr: array,
      add: false,
      edit: false,
      editorOption: {
        placeholder: '请在这里输入',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote', 'code-block'], // 引用，代码块
            ['image'] // 上传图片、上传视频
          ]
        }
      },

      questionForm: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        // 选项
        options: [],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: ''
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        province: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }]
      },
      subjectOption: [],
      catalogOption: [],
      companyOption: [],
      provincesOption: [],
      areaOption: [],
      directionOption: direction,
      questionTypeOption: questionType,
      difficultyOption: difficulty,
      tagsOption: []
    }
  },
  methods: {
    async simpleSubject () {
      const { data } = await simpleSubject()
      this.subjectOption = data
    },
    async focusSubject () {
      const { data } = await list({ subjectID: this.questionForm.subjectID })
      this.catalogOption = data.items
    },
    async companyList () {
      const { data } = await companyList()

      this.companyOption = data.items
    },
    async provinces () {
      const res = await provinces()

      this.provincesOption = res
    },
    async changeCity () {
      const res = await citys(this.questionForm.province)
      this.areaOption = res
      this.questionForm.city = this.areaOption[0]
    },

    //  提交选项
    async onSubmit () {
      // 标签转字符串
      this.questionForm.tags = this.questionForm.tags.join(',')
      // 试题选项操作 处理数据

      // 单选
      if (this.questionForm.questionType === '1') {
        const optionArr = this.arr.slice(0, 4)
        // 判断默认勾选
        optionArr.forEach((item, index) => {
          if (index === this.radio) {
            item.isRight = true
          } else {
            item.isRight = false
          }
        })
        this.questionForm.options = optionArr
      } else if (this.questionForm.questionType === '2') {
        const arr = this.arr.slice(0, this.questionIndex)
        // 判断默认勾选
        for (let i = 0; i < arr.length; i++) {
          this.checkList.forEach(item => {
            if (i === item) {
              arr[i].isRight = true
            }
          })
        }
        this.questionForm.options = arr
      }

      await add(this.questionForm)
    },

    //  添加选项
    addItem () {
      if (this.questionIndex > 25) {
        return
      }
      this.questionIndex++
    },
    async simpleTag () {
      const { data } = await simpleTag()

      this.tagsOption = data
    },

    async save (e) {
      await this.$refs.formRef.validate()

      if (e.target.innerText === '确认提交') {
        this.onSubmit()
        this.$message.success('添加成功')
        this.$router.push('list')
      } else if (e.target.innerText === '确认修改') {
        // 标签转字符串
        this.questionForm.tags = this.questionForm.tags.join(',')

        // 试题选项操作 处理数据
        if (this.questionForm.questionType === '1') {
          const optionArr = this.arr.slice(0, 4)
          // 判断默认勾选
          optionArr.forEach((item, index) => {
            if (index === this.radio) {
              item.isRight = true
            } else {
              item.isRight = false
            }
          })
          this.questionForm.options = optionArr.reverse()
        } else if (this.questionForm.questionType === '2') {
          const arr = this.arr.slice(0, this.questionIndex)
          // 判断默认勾选
          for (let i = 0; i < arr.length; i++) {
            this.checkList.forEach(item => {
              if (i === item) {
                arr[i].isRight = true
              }
            })
          }
          this.questionForm.options = arr.reverse()
        }
        await update(this.questionForm)

        this.$message.success('修改成功')
        this.$router.go(-1)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.test-questions {
  margin: 20px 20px;
  .header {
    .hr-line {
      color: #ebeef5;
    }
  }
  .el-form {
    .el-select {
      width: 100%;
    }
    .upload-demo {
    margin-left: 20px;
    .upload_btn {
      margin-top: -10px;
      height: 50px;
    }

  }
  .add_btn {
    margin: 10px 0px 20px;
    margin-left: 120px;
  }
  }
}
</style>
